import Modifieritem from '../business/modifieritem';
import lodash from 'lodash';

export default class Modifiers {
  constructor(modifiers) {
    this.items = [];
    this._initItems(modifiers);
  }

  //getter&&setter
  get amount() {
    // debugger
    const _self = this;
    let _amount = 0;
    _self.items.forEach(function(elem, i) {
      _amount += elem.amount;
    });
    return _amount;
  }

  _initItems(modifiers) {
    const _self = this;
    modifiers && modifiers.forEach((elem) => {
      let modifieritem = new Modifieritem(elem);
      _self.items.push(modifieritem);
    });
  }

  pushModifiersItem(modifieritem) {
    this.items.push(modifieritem);
  }

  setOptionsOfSingleselect(modifierID, option) {
    this.items.forEach((elem) => {
      if (elem.id == modifierID) {
        elem.options[0] = option;
        elem.amount = option.price;
      }
    });
  }

  mergeModifiers(modifiers) {
    //todo 通用算法
    //删除以前的
    const self = this;
    this.items.splice(0, this.items.length);
    modifiers.items.forEach(v => {
      self.items.push(v);
    })

  }

  copyModifiers(modifiers) {
    const self = this;
    modifiers.items.forEach((v, i) => {
      v.options.forEach(vv => {
        self.items[i].addOption(vv);
      })
    })
  }

  generateOption(modifierId, option) {

    var items = this.items;
    for (var i = 0, l = items.length; i < l; i++) {
      var item = items[i];
      if (item.id == modifierId) {
        //单选
        if (item.singleton) {
          this._generateOptionOfSingleton(i, option)
        } else {
          this._generateOptionOfNoSingleton(i, option)
        }
        break;
      }
    }
  }

  //单选
  _generateOptionOfSingleton(index, option) {
    var item = this.items[index];
    item.removeOptionAll();
    item.addOption(option);
  }

  //非单选
  _generateOptionOfNoSingleton(index, option) {
    var item = this.items[index];
    var options = this.items[index].options;
    for (var i = 0, l = options.length; i < l; i++) {
      if (options[i].id == option.id) {
        item.removeOption(option);
        return;
      }
    }
    item.addOption(option);
  }


  static getModifiersOfNoRequired(modifiers) {
    let res = [];
    for (var i = 0, l = modifiers.items.length; i < l; i++) {
      if (modifiers.items[i].isRequired == true && !modifiers.items[i].options
        .length) {
        res.push(modifiers.items[i]);
      }
    }
    return res;
  }

  toJSON() {
    return lodash.extend({}, lodash.clone(this), {
      amount: this.amount,
      items: lodash.filter(this.items, item => {
        return item.amount >= 0 && item.options.length > 0;
      })
    });
  }
}
